<template>
  <Teleport to="body">
    <!-- <Transition name="modal" appear> -->
    <div v-if="isVisible" class="modal-overlay" @click="handleOverlayClick">
      <div class="modal-container" :class="{ 'mobile-fullscreen': isMobile }" @click.stop>
        <div class="login-modal-content">
          <div class="close-btn-wrapper">
            <svg
              @click="handleOverlayClick"
              xmlns="http://www.w3.org/2000/svg"
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none">
              <path d="M6 6L18 18" stroke="#222222" stroke-width="1.5" stroke-linecap="round" />
              <path d="M18 6L6 18" stroke="#222222" stroke-width="1.5" stroke-linecap="round" />
            </svg>
          </div>
          <div class="login-content mt-[10px] px-[24px]">
            <!-- 邮箱输入步骤 -->
            <div v-if="step === 1" class="">
              <div class="step-header">
                <div class="step-title">Enter your email to continue</div>
                <p class="step-subtitle">An account will be automatically created for new users.</p>
              </div>

              <div class="form-section">
                <div class="form-group">
                  <label class="form-label">Email address</label>
                  <el-input
                    v-model="email"
                    placeholder="Enter your Email address"
                    type="email"
                    size="large"
                    class="email-input"
                    :class="{ 'is-error': emailError }"
                    @input="clearEmailError"
                    @keyup.enter="handleGetVerificationCode" />
                  <div v-if="emailError" class="error-message">
                    {{ emailError }}
                  </div>
                </div>

                <!-- <button :loading="isLoading" :disabled="!isEmailValid || isLoading" @click="handleGetVerificationCode"
                    class="submit-btn">
                    <span>Get Verification Code</span>
                  </button> -->

                <el-button
                  type="primary"
                  size="large"
                  :loading="isLoading"
                  :disabled="!isEmailValid || isLoading"
                  @click="handleGetVerificationCode"
                  class="w-full h-[48px] text-base font-medium"
                  style="border-radius: 30px">
                  <span v-if="!isLoading" class="get_code_text">Get Verification Code</span>
                </el-button>
              </div>

              <!-- 协议条款 -->
              <div class="agreement-section agreement_view">
                <div @click="agreed = !agreed" class="mr-[4px]">
                  <AgreeIcon :agreed="agreed" />
                </div>
                <p class="agreement-text ml-[4px]">
                  By continuing, you agree to our
                  <span class="color_text cursor-pointer" @click="goTerms">Terms of Service</span>
                  and
                  <span class="color_text cursor-pointer" @click="goPrivacy">Privacy Policy</span>
                </p>
              </div>
            </div>

            <!-- 验证码输入步骤 -->
            <div v-else-if="step === 2" class="">
              <div class="step-header text-center">
                <h2 class="step-title">Verify your email</h2>
                <p class="step-subtitle">Enter the verification code sent to your email</p>
                <div @click="step = 1" class="email-display">
                  <span class="email_text cursor-pointer">{{ email }}</span>
                  <EditIcon class="ml-[3px]" />
                </div>
              </div>

              <div class="form-section">
                <VerificationCodeInput
                  v-model="verificationCode"
                  :error="codeError"
                  @complete="handleVerifyCode" />
                <!-- 倒计时显示 -->
                <div class="countdown-text mt-[24px] text-center">
                  <span class="cursor-pointer email_text" @click="handleResendCode">
                    Didn't receive a code?
                  </span>
                  <span class="cursor-pointer email_text" @click="handleResendCode">Resend</span>
                  <span v-if="countdown > 0">({{ countdown }})</span>
                </div>
              </div>
            </div>

            <!-- 谷歌登录 -->
            <div>
              <div class="py-[8px]">
                <el-divider content-position="center">Or</el-divider>
              </div>

              <button
                class="google-btn w-full"
                @click="loginWithGoogle"
                :disabled="isGoogleLoading">
                <img
                  src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg"
                  alt="google" />
                {{ isGoogleLoading ? 'Login...' : 'Continue with Google' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- </Transition> -->
    <AgreeModal v-if="showAgreeModal" @cancel="showAgreeModal = false" @agree="agreeAgreeModal" />
  </Teleport>
</template>

<script setup lang="ts">
  import Logo from '@/components/icons/logo.vue';
  import { ref, computed, onUnmounted, watch, onMounted } from 'vue';
  import { Close, Edit } from '@element-plus/icons-vue';
  import VerificationCodeInput from '@/components/VerificationCodeInput.vue';
  import { useLoginModalStore } from '@/store/loginModal';
  import { useUserStore } from '@/store/user';
  import { UserAPI } from '@/api/user';
  import type { LoginFormData, LoginStep } from '@/types/login';
  import { useRouter } from 'vue-router';
  import EditIcon from '@/components/icons/EditIcon.vue';
  import AgreeIcon from '@/components/icons/AgreeIcon.vue';
  import AgreeModal from '@/components/AgreeModal.vue';
  import { useGoogleLogin } from '@/composables/useGoogleLogin';

  // 2634674263@qq.com

  const router = useRouter();
  // 使用 store
  const loginModalStore = useLoginModalStore();
  const userStore = useUserStore();

  const { loginWithGoogle, isGoogleLoading } = useGoogleLogin();

  // 响应式数据
  const email = ref('');
  const verificationCode = ref('');
  const emailError = ref('');
  const codeError = ref('');
  const agreed = ref(false);
  const step = ref<1 | 2>(1);
  const countdown = ref(0);
  const showAgreeModal = ref<boolean>(false); // 隐私协议modal

  // 计算属性
  const isVisible = computed(() => loginModalStore.visible);
  const isLoading = computed(() => loginModalStore.loading);

  const isEmailValid = computed(() => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email.value);
  });

  const isMobile = computed(() => {
    return window.innerWidth <= 768;
  });

  // 定时器
  let countdownTimer: any = null;

  // 监听弹窗显示状态，重置表单
  watch(isVisible, (visible) => {
    if (visible) {
      resetForm();
    }
  });

  // 隐私协议modal
  const agreeAgreeModal = () => {
    showAgreeModal.value = false;
    agreed.value = true;
    handleGetVerificationCode();
  };

  // 方法
  const resetForm = () => {
    email.value = '';
    verificationCode.value = '';
    emailError.value = '';
    codeError.value = '';
    agreed.value = false;
    step.value = 1;
    countdown.value = 0;
    if (countdownTimer) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
  };

  const clearEmailError = () => {
    emailError.value = '';
  };

  const validateEmail = () => {
    if (!email.value) {
      emailError.value = 'Please enter your email address';
      return false;
    }
    if (!isEmailValid.value) {
      emailError.value = 'Please enter a valid email address';
      return false;
    }
    return true;
  };

  const startCountdown = () => {
    countdown.value = 60;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer!);
        countdownTimer = null;
      }
    }, 1000);
  };

  const handleGetVerificationCode = async () => {
    if (!validateEmail()) return;

    // 检查协议是否同意
    if (!agreed.value) {
      showAgreeModal.value = true;
      return;
    }

    loginModalStore.setLoading(true);
    emailError.value = '';
    verificationCode.value = '';
    try {
      // 调用真实API获取验证码
      await UserAPI.getCode({
        email: email.value,
      });

      step.value = 2;
      startCountdown();
    } catch (error: any) {
      console.error('Send verification code error:', error);
    } finally {
      loginModalStore.setLoading(false);
    }
  };

  const handleVerifyCode = async (code?: string) => {
    const codeToVerify = code || verificationCode.value;

    if (!codeToVerify || codeToVerify.length !== 6) {
      codeError.value = 'Please enter a complete 6-digit code';
      return;
    }

    loginModalStore.setLoading(true);
    codeError.value = '';

    try {
      // 调用真实API进行登录
      const res = await UserAPI.login({
        email: email.value,
        code: codeToVerify,
        source_type: 2,
      });

      console.log('登录响应:', res);

      // 存储用户信息到store（自动持久化）
      // 注意：这里需要根据实际API返回结构调整
      userStore.loginSuccess(res);

      loginModalStore.handleLoginSuccess();
    } catch (error: any) {
      codeError.value = 'Invalid verification code';
      console.error('Verify code error:', error);
    } finally {
      loginModalStore.setLoading(false);
    }
  };

  const handleResendCode = async () => {
    if (countdown.value > 0) return;
    await UserAPI.getCode({
      email: email.value,
    });
    startCountdown();
  };

  const goTerms = () => {
    router.push('/terms');
  };

  const goPrivacy = () => {
    router.push('/privacy');
  };

  const handleClose = () => {
    loginModalStore.hideModal();
  };

  const handleOverlayClick = () => {
    handleClose();
  };

  // 键盘事件处理
  const handleKeydown = (event: KeyboardEvent) => {
    if (event.key === 'Escape' && isVisible.value) {
      handleClose();
    }
  };

  // 滚动锁定
  const lockScroll = () => {
    document.body.style.overflow = 'hidden';
  };

  const unlockScroll = () => {
    document.body.style.overflow = '';
  };

  // 监听弹窗显示状态
  watch(isVisible, (visible) => {
    if (visible) {
      lockScroll();
      document.addEventListener('keydown', handleKeydown);
    } else {
      unlockScroll();
      document.removeEventListener('keydown', handleKeydown);
    }
  });

  // 清理定时器和事件监听
  onUnmounted(() => {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
    document.removeEventListener('keydown', handleKeydown);
    unlockScroll();
  });
</script>

<style lang="scss" scoped>
  .agree_content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .agree_view {
    width: 440px;
    background: #fff;
    padding: 32px;
    border-radius: 16px;
    //position: absolute;
    //top: 50%; /* 顶部距离父容器 50% */
    //left: 50%; /* 左侧距离父容器 50% */
    //transform: translate(-50%, -50%); /* 向左、上偏移自身 50% */
    z-index: 300000;

    .title {
      color: var(---9, #0a0a0a);
      font-family: 'Inter Tight';
      font-size: 24px;
      font-style: normal;
      font-weight: 700;
      line-height: normal;
    }

    .des_text {
      color: var(---6, #7a7a7a);

      font-family: 'Inter Tight';
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: 150%;
      /* 24px */
    }
  }

  .agreement_view {
    display: flex;
    flex-direction: row;
  }

  .email_text {
    color: #7a7a7a !important;
    font-size: 16px;
  }

  .email_text:hover {
    color: #0a0a0a !important;
    text-decoration: underline;
  }

  // 遮罩层
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px); // Safari 支持
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    // 优化性能
    will-change: opacity;
  }

  // 弹窗容器
  .modal-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    max-width: 568px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
    // 确保 transform 原点在中心，动画更流畅
    transform-origin: center center;
    will-change: transform, opacity;

    &.mobile-fullscreen {
      max-width: none;
      width: 100vw;
      height: 100vh;
      height: 100dvh; // 支持 iOS 动态视口
      border-radius: 0;
      max-height: none;
      // iOS 安全区内边距，避免被刘海/系统栏遮挡
      padding-top: env(safe-area-inset-top);
      padding-bottom: env(safe-area-inset-bottom);
      padding-left: env(safe-area-inset-left);
      padding-right: env(safe-area-inset-right);
      // 移动端从底部滑入，transform 原点在底部
      transform-origin: center bottom;
    }
  }

  .close-btn-wrapper {
    // 基础内边距 + 安全区内边距，确保顶部按钮在 iOS 可见
    padding-top: calc(12px + env(safe-area-inset-top));
    padding-left: calc(12px + env(safe-area-inset-left));
    padding-right: calc(12px + env(safe-area-inset-right));
    // 兼容旧版 iOS（constant 已弃用，但可作为兜底）
    padding-top: calc(12px + constant(safe-area-inset-top));
  }

  // 关闭按钮
  .modal-header {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;

    .close-btn {
      cursor: pointer;
      color: #7a7a7a;

      &:hover {
        color: #f76b1b;
      }
    }
  }

  // 登录内容样式已通过内联样式设置

  // 丝滑动画效果
  // 进入动画 - 使用更平滑的缓动函数
  .modal-enter-active {
    // 遮罩层淡入
    transition: opacity 0.35s cubic-bezier(0.4, 0, 0.2, 1);

    // 桌面端容器动画 - 弹性效果
    .modal-container:not(.mobile-fullscreen) {
      transition: transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1),
        opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    // 移动端容器动画 - 从底部滑入，使用更自然的缓动
    .modal-container.mobile-fullscreen {
      transition: transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94),
        opacity 0.35s cubic-bezier(0.4, 0, 0.2, 1);
    }
  }

  // 离开动画 - 快速且流畅
  .modal-leave-active {
    // 遮罩层淡出
    transition: opacity 0.25s cubic-bezier(0.4, 0, 1, 1);

    // 桌面端容器动画
    .modal-container:not(.mobile-fullscreen) {
      transition: transform 0.25s cubic-bezier(0.4, 0, 1, 1),
        opacity 0.25s cubic-bezier(0.4, 0, 1, 1);
    }

    // 移动端容器动画 - 快速滑出
    .modal-container.mobile-fullscreen {
      transition: transform 0.3s cubic-bezier(0.55, 0.06, 0.68, 0.19),
        opacity 0.25s cubic-bezier(0.4, 0, 1, 1);
    }
  }

  // 进入动画初始状态
  .modal-enter-from {
    opacity: 0;

    // 桌面端：轻微缩放 + 上移，更精致的动画（使用 translate3d 启用 GPU 加速）
    .modal-container:not(.mobile-fullscreen) {
      opacity: 0;
      transform: scale(0.96) translate3d(0, -8px, 0);
    }

    // 移动端全屏：从底部滑入（使用 translate3d 启用 GPU 加速）
    .modal-container.mobile-fullscreen {
      opacity: 0;
      transform: translate3d(0, 100%, 0);
    }
  }

  // 离开动画结束状态
  .modal-leave-to {
    opacity: 0;

    // 桌面端：轻微缩放 + 上移（使用 translate3d 启用 GPU 加速）
    .modal-container:not(.mobile-fullscreen) {
      opacity: 0;
      transform: scale(0.96) translate3d(0, -8px, 0);
    }

    // 移动端全屏：滑到底部（使用 translate3d 启用 GPU 加速）
    .modal-container.mobile-fullscreen {
      opacity: 0;
      transform: translate3d(0, 100%, 0);
    }
  }

  // 动画结束状态
  .modal-enter-to,
  .modal-leave-from {
    opacity: 1;

    // 桌面端：正常状态（使用 translate3d 启用 GPU 加速）
    .modal-container:not(.mobile-fullscreen) {
      opacity: 1;
      transform: scale(1) translate3d(0, 0, 0);
    }

    // 移动端：正常状态（使用 translate3d 启用 GPU 加速）
    .modal-container.mobile-fullscreen {
      opacity: 1;
      transform: translate3d(0, 0, 0);
    }
  }

  .step-header {
    margin-bottom: 24px;

    .step-title {
      font-size: 22px;
      font-weight: 700;
      color: #0a0a0a;
      margin: 0 0 12px 0;
    }

    .step-subtitle {
      color: #7a7a7a;
      font-size: 14px;
      margin-top: 16px;
    }

    .email-display {
      display: flex;
      align-items: center;
      justify-content: center;

      .edit-icon {
        cursor: pointer;
        transition: color 0.3s ease;

        &:hover {
          color: #f76b1b;
        }
      }
    }
  }

  .form-section {
    margin-bottom: 8px;
  }

  .form-group {
    margin-bottom: 16px;

    .form-label {
      display: block;
      font-size: 14px;
      color: #0a0a0a;
      margin-bottom: 8px;
    }
  }

  .email-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      border: none;
      box-shadow: none;
      transition: all 0.3s ease;
      background: #f4f5f7;
      height: 48px;

      // &:hover {
      //   border-color: #f76b1b;
      // }

      // &.is-focus {
      //   border-color: #f76b1b;
      //   box-shadow: 0 0 0 2px rgba(247, 107, 27, 0.1);
      // }
    }

    &.is-error :deep(.el-input__wrapper) {
      border-color: #f56565;
      box-shadow: 0 0 0 2px rgba(245, 101, 101, 0.1);
    }
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    border-radius: 30px;
    font-size: 16px;
    font-weight: 700;
    background-color: #cbcbcb;
    cursor: pointer;
    color: #fff;

    :deep(.el-button) {
      background: #f76b1b;
      border-color: #f76b1b;

      &:hover {
        background: #e55a0f;
        border-color: #e55a0f;
      }

      &:disabled {
        background: #cbcbcb;
        border-color: #cbcbcb !important;
        color: #fff;
      }
    }
  }

  .agreement-section {
    .agreement-text {
      font-size: 14px;
      color: #7a7a7a;
      line-height: 1.5;
      margin: 0;

      .link {
        color: #f76b1b;
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }

  .countdown-text {
    color: #7a7a7a;
    font-size: 14px;
    //margin-top: 24px;
  }

  .error-message {
    color: #f56565;
    font-size: 12px;
    margin-top: 8px;
  }

  // 协议勾选框警告样式
  :deep(.el-checkbox) {
    &.agreement-warning {
      .el-checkbox__input {
        .el-checkbox__inner {
          border-color: #f56565 !important;
          background-color: #fef2f2 !important;
          animation: shake 0.5s ease-in-out;
        }
      }
    }
  }

  :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;

    &.el-button--primary {
      background: #f76b1b;
      border-color: #f76b1b;

      &:hover {
        background: #e55a0f;
        border-color: #e55a0f;
      }

      &:disabled {
        background: #e0e0e0;
        border-color: #e0e0e0;
        color: #9ca3af;
      }
    }
  }

  // 抖动动画
  @keyframes shake {
    0%,
    100% {
      transform: translateX(0);
    }

    10%,
    30%,
    50%,
    70%,
    90% {
      transform: translateX(-3px);
    }

    20%,
    40%,
    60%,
    80% {
      transform: translateX(3px);
    }
  }

  .get_code_text {
    color: var(---0, #fff);
    font-family: 'InterTight';
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
  }

  .color_text {
    color: #f76b1b;
    border-bottom: 1px solid #f76b1b;
    padding-bottom: 1px;
  }

  .color_text:hover {
    color: #e55c0d;
    border-bottom: 1px solid #e55c0d;
  }

  .google-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    width: 100%;
    height: 48px;
    padding: 0 24px;
    border-radius: 30px;
    background: #fff;
    color: #7a7a7a;
    font-size: 16px;
    background-color: #f4f5f7;
    font-weight: 500;
    font-family: 'InterTight';
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover:not(:disabled) {
      background: #f8f9fa;
    }

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    img {
      width: 20px;
      height: 20px;
    }
  }

  :deep(.el-divider__text) {
    font-size: 14px;
    color: #7a7a7a;
  }
</style>
